import { Request, Response, NextFunction } from 'express'
import RedisServer from "./redis";
import { parseToken } from './jwt'
import { pathWhite } from './contant'
import {tokenParams} from "../../global";
import { userCountDao } from '../dao/userDao'
const verify = async (req: Request, res: Response, next: NextFunction) => {
    const token = req.headers[process.env.NODE_MANAGE_TOKEN as string]
    const path = req.path
    if (pathWhite.includes(path)) {
        next()
    } else {
        if (token) {
            const params = parseToken(token as string)
            if (params.code === 200) {
                const count = await userCountDao([(params as tokenParams).email])
                count[0].count === 0 ? res.send({ code: 501, message: '用户不存在', data: null }) :
                RedisServer.redisGet(`token:${(params as tokenParams).email}`).then(redisToken => {
                    if(redisToken && redisToken === token) {
                        next()
                    } else {
                        res.send({ code: 501, message: '请重新登录', data: null })
                    }
                })
            } else {
                res.send({ code: 501, message: '请重新登录', data: null })
            }
        } else {
            res.send({ code: 501, message: '请先登录', data: null })
        }
    }
}

export default verify